package com.example.newhabitclock.HabitItemRecyclerViewPackage

import android.graphics.Color
import android.os.Build
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AlertDialog
import androidx.lifecycle.LifecycleOwner
import androidx.recyclerview.widget.RecyclerView
import com.example.newhabitclock.HabitRoomPackage.Habit
import com.example.newhabitclock.MainViewModel
import com.example.newhabitclock.databinding.DialogHabitCheckInBinding
import com.example.newhabitclock.databinding.HabitItemBinding
import java.time.LocalDate

class HabitAdapter : RecyclerView.Adapter<HabitAdapter.MyViewHolder>() {
    //用来接受外部传入的数据(HabitModel类)
    private var myDataList: List<HabitModel> = listOf()

    //保存闹铃按钮与删除按钮的显示状态
    var itemIconShowState: Boolean = true

    //用来获取外部传入的MainViewModel对象,用于调用其中的updateHabit方法更新数据库中的数据
    private lateinit var myViewModel: MainViewModel
    private lateinit var myLifecycleOwner: LifecycleOwner

    //用来保存当前需要删除的那个习惯卡片信息 后续删除
    private lateinit var cutHabitCard: Habit

    //用来保存当前需要闹铃提醒的那个习惯卡片信息
    private lateinit var callingHabitCard: Habit

    //接受Room数据库中的习惯数据
    private var myRoomListInfo: List<Habit> = emptyList()

    inner class MyViewHolder(private val mBinding: HabitItemBinding) :
        RecyclerView.ViewHolder(mBinding.root) {
        @RequiresApi(Build.VERSION_CODES.O)
        fun bind(myHabitModel: HabitModel) {
            mBinding.habitName.text = myHabitModel.habitName
            mBinding.habitTime.text = myHabitModel.habitTime
            mBinding.habitRepeatDays.text = "每周${myHabitModel.habitRepeatDays.toString()}"

            //先移除旧的Switch按钮监听器
            mBinding.habitSwitchButton.setOnCheckedChangeListener(null)
            //点击习惯卡片删除图标
            mBinding.habitRubbish.setOnClickListener {
                myViewModel.allHabits.observe(myLifecycleOwner) { habitList ->
                    habitList.forEach { habit ->
                        if (myHabitModel.habitName == habit.name && myHabitModel.habitTime == habit.time && myHabitModel.habitRepeatDays == habit.repeatDays) {
                            cutHabitCard = habit
                        }
                    }
                }
                //将该习惯删除，并同步Room数据库中的数据一并删除
                myViewModel.deleteHabit(cutHabitCard)
                //删除某个习惯卡片后 界面中的响铃按钮会重新出现 删除图标消失
                //刷新重新判断使得图标显示正确
                itemIconShowState = false
                notifyDataSetChanged()
            }

            //每个 item 的 bind 方法只处理当前 myHabitModel 的数据
            //每个 ViewHolder 都有自己的 mBinding 对象,不会影响到其他 ViewHolder
            if (myHabitModel.isCheckIn) {
                mBinding.backgroundItem.setBackgroundColor(Color.parseColor("#E8F5E9"))
            } else {
                mBinding.backgroundItem.setBackgroundColor(Color.parseColor("#FFFFFF"))
            }

            if (itemIconShowState) {
                mBinding.habitSwitchButton.visibility = View.VISIBLE
                mBinding.habitRubbish.visibility = View.INVISIBLE
            }
            if (!itemIconShowState) {
                mBinding.habitSwitchButton.visibility = View.INVISIBLE
                mBinding.habitRubbish.visibility = View.VISIBLE
            }

            /*mBinding.habitSwitchButton.setOnCheckedChangeListener { _, isChecked ->
                Log.v("pxd","$isChecked")
                myRoomListInfo.forEach { habit ->
                    if (myHabitModel.habitName == habit.name && myHabitModel.habitTime == habit.time && myHabitModel.habitRepeatDays == habit.repeatDays) {
                        callingHabitCard = habit  //保存当前的习惯卡片item
                        if (isChecked) { //用户开启闹铃按钮即可开启提醒
                            //开启闹铃提醒
                            callingHabitCard.isCallIn = true
                        } else {
                            callingHabitCard.isCallIn = false //不用闹铃提醒
                        }
                        myHabitModel.isCallIn = isChecked
                        mBinding.habitSwitchButton.isChecked = isChecked
                        myViewModel.updateHabit(callingHabitCard)
                    }
                }
                Log.v("pxd","${callingHabitCard.isCallIn}")
                notifyDataSetChanged()
            }*/
        }
    }

    //寻找当前item对应的habit
    fun findCurrentHabitList(habits: List<Habit>) {
        myRoomListInfo = habits
        notifyDataSetChanged()
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
        val binding = HabitItemBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        return MyViewHolder(binding)
    }

    override fun getItemCount(): Int {
        return myDataList.size
    }

    @RequiresApi(Build.VERSION_CODES.O)
    override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
        val myItem = myDataList[position]
        //给每个item设置点击事件，进行打卡操作（holder.itemView获取每个习惯卡片的视图）
        holder.itemView.setOnClickListener {
            //配置打卡弹窗信息数据
            val context = holder.itemView.context
            val dialogHabitCheckInBinding =
                DialogHabitCheckInBinding.inflate(LayoutInflater.from(context))
            dialogHabitCheckInBinding.habitName.text = myItem.habitName
            dialogHabitCheckInBinding.habitTime.text = myItem.habitTime
            //数据配置完毕，点击卡片显示打卡弹窗
            val alertDialogView = AlertDialog.Builder(context).create()
            alertDialogView.apply {
                this.setView(dialogHabitCheckInBinding.root)
                this.show()
            }
            //点击打卡完成按钮
            dialogHabitCheckInBinding.finishButton.setOnClickListener {
                //将该习惯今日的打卡记录修改为true(Room数据库中的数据，而不是外部传入的传递性数据)
                myViewModel.allHabits.value?.forEach { habit ->
                    if (habit.name == myItem.habitName && habit.time == myItem.habitTime && myItem.habitRepeatDays == habit.repeatDays && habit.isCheckIn == false) {
                        habit.isCheckIn = true
                        myItem.isCheckIn = true
                        //调用updateHabit方法更新Room数据库中的信息
                        myViewModel.updateHabit(habit)

                        //打卡成功 记录当前日期 并保存到数据库中
                        val currentDate = LocalDate.now().toString()  //获取当前的日期
                        myViewModel.insertCheckInRecord(habit.id,currentDate)

                        Toast.makeText(context, "打卡成功", Toast.LENGTH_SHORT).show()
                        //点击完按钮就隐藏打卡弹窗
                        alertDialogView.dismiss()
                    } else if (habit.name == myItem.habitName && habit.time == myItem.habitTime && myItem.habitRepeatDays == habit.repeatDays && habit.isCheckIn) {
                        Toast.makeText(context, "今日已打卡完毕", Toast.LENGTH_SHORT).show()
                        //点击完按钮就隐藏打卡弹窗
                        alertDialogView.dismiss()
                    }
                }
            }
            //点击打卡失败按钮
            dialogHabitCheckInBinding.failureButton.setOnClickListener {
                //点击打卡失败之前先判断今天是否已经打卡成功
                myViewModel.allHabits.value?.forEach { habit ->
                    if (myItem.habitName == habit.name && myItem.habitTime == habit.time && myItem.habitRepeatDays == habit.repeatDays && habit.isCheckIn) {
                        Toast.makeText(context, "今日已打卡完毕", Toast.LENGTH_SHORT).show()
                        //点击完按钮就隐藏打卡弹窗
                        alertDialogView.dismiss()
                    } else if (myItem.habitName == habit.name && myItem.habitTime == habit.time && myItem.habitRepeatDays == habit.repeatDays && !habit.isCheckIn) {
                        Toast.makeText(context, "打卡失败", Toast.LENGTH_SHORT).show()
                        //点击完按钮就隐藏打卡弹窗
                        alertDialogView.dismiss()
                    }
                }

            }
        }

        //监听习惯卡片今日是否打卡完毕（完毕则改变卡片颜色为绿色）
        myViewModel.allHabits.observe(myLifecycleOwner) { habitList ->
            habitList.forEach { habit ->
                if (myItem.habitName == habit.name && myItem.habitTime == habit.time && myItem.habitRepeatDays == habit.repeatDays && habit.isCheckIn) {
                    //仅仅修改该myItem的背景颜色，该怎么实现
                    myItem.isCheckIn = true
                }
            }
        }
        //等每个item的isCheckIn状态修改完毕时，进行绑定
        holder.bind(myItem)
    }

    //外部获取这个方法，并传入数据
    fun getData(myHabitList: List<HabitModel>) {
        myDataList = myHabitList
        //刷新界面
        notifyDataSetChanged()
    }

    fun getMainViewModel(viewModel: MainViewModel, lifecycleOwner: LifecycleOwner) {
        myViewModel = viewModel
        myLifecycleOwner = lifecycleOwner
    }

    //用于外部编辑习惯时修改闹铃按钮和删除按钮的视图显示
    fun changeItemShowState(temp: Boolean) {
        //获取外部此时需要显示的状态
        itemIconShowState = temp
        notifyDataSetChanged()
    }
}